import Immutable from 'immutable';
import { routerRedux } from 'dva/router';
import {
  login,
  smsCode,
  logout,
  queryBalance,
  querySumGift,
  loginWithCode,
} from '../services/user';
import { queryUserCouponTotal } from '../services/coupon';
// import toast from '../utils/toast';
import { get, save, clear } from '../utils/storage';
import {
  SMS_TIMEOUT,
  IS_LOCAL,
} from '../constants/setting';
import { delay } from '../utils/func';


const UserRecord = Immutable.Record({
  token: null,
  // token: 'c801bf46ba2147dbaf0f8c479dc4c963youyuer_cm_token',
  mobile: null,
  nickName: null,
  fromTmall: false,
});

export class User extends UserRecord {
  save() {
    save('user', this);
  }
  static init() {
    if (IS_LOCAL) { // 本地调试写死token，免去登录麻烦
      return new User({
        // token: 'b5d7a98c1bb446b68a286281f2b3d7b9youyuer_cm_token', // open
        token: 'f8f8df3636e54c8ba43bc80efe49f329youyuer_cm_token', // dev baafaf20c6554131b3a1a5d2c48d720eyouyuer_cm_token f8f8df3636e54c8ba43bc80efe49f329youyuer_cm_token
      });
    } else {
      return new User(get('user'));
    }
  }
  static clear() {
    clear('user');
  }
}


export default {
  namespace: 'user',

  state: Immutable.fromJS({
    user: User.init(),
    sms: 0,
    verToken: null,
    account: {
      balance: 0,
    },
    gift: {
      sum: 0,
      couponAmount: 0,
      couponCount: 0,
      activationCount: 0,
    },
    yyeCode: null,

  }),

  effects: {
    *loginWithCode({ payload }, { call, put }) {
      User.clear();
      yield put({
        type: 'updateUser',
        payload: null,
      });
      yield put({
        type: 'updateCode',
        payload: payload.yyeCode,
      });
      const { fromTmall, redirect, ...rest } = payload;
      const res = yield call(loginWithCode, rest);
      if (res.success) {
        yield put({
          type: 'updateUser',
          payload: { ...res.data, fromTmall },
        });
        yield put(routerRedux.replace(redirect));
      } else {
        yield put(routerRedux.replace(`/app/500?msg=登录失败:${res.msg}`));
      }
    },
    *fetchUserCouponTotal({ payload }, { call, put }) {
      const res = yield call(queryUserCouponTotal, payload);
      if (res.success) {
        yield put({
          type: 'updateCouponTotal',
          payload: res.data,
        });
      }
    },
    *fetchSumGift({ payload }, { call, put }) {
      const res = yield call(querySumGift, payload);
      if (res.success) {
        yield put({
          type: 'updateSumGift',
          payload: res.data,
        });
      }
    },
    *fetchBalance({ payload }, { call, put }) {
      const res = yield call(queryBalance, payload);
      if (res.success) {
        yield put({
          type: 'updateBalance',
          payload: res.data,
        });
      }
    },
    *login({ payload }, { call, put }) {
      const { redirect = 'home', ...rest } = payload;
      const res = yield call(login, rest);
      if (res.success) {
        yield put({
          type: 'updateUser',
          payload: res.data,
        });
        if (redirect) {
          if (redirect.startsWith('http')) {
            yield window.location.href = redirect;
          } else {
            yield put(routerRedux.push(redirect));
          }
        } else {
          yield put(routerRedux.goBack());
        }
      }
    },
    *logout(_, { put, call, select }) {
      const token = yield select(state => state.user.getIn(['user', 'token']));
      if (token) {
        const res = yield call(logout);
        if (res.success) {
          yield put({
            type: 'updateCode',
            payload: res.data.yyeCode,
          });
        }
      }
      User.clear();
      yield put({
        type: 'updateUser',
        payload: null,
      });
    },
    // 发送短信验证码
    sendSmsCode: [function*({ payload }, { call, put, select }) {
      const sms = yield select(state => state.user.get('sms'));
      if (sms === 0) {
        const res = yield call(smsCode, payload);
        if (res.success) {
          yield put({
            type: 'updateSmsLeftTime',
            payload: { time: SMS_TIMEOUT, verToken: res.data.verToken },
          });
          yield put({ type: 'smsCountDown' });
        }
      }
    }, { type: 'throttle', ms: 4000 }],
    // 短信验证码倒计时
    smsCountDown: [function* (_, { put, select }) {
      const sms = yield select(state => state.user.get('sms'));
      if (sms > 0) {
        yield put({
          type: 'updateSmsLeftTime',
          payload: { time: sms - 1 },
        });
        yield delay(1000);
        yield put({ type: 'smsCountDown' });
      }
    }, { type: 'takeEvery' }],
  },

  reducers: {
    updateCode(state, { payload }) {
      return state.set('yyeCode', payload);
    },
    updateCouponTotal(state, { payload }) {
      return state.mergeIn(['gift'], {
        couponAmount: payload.amount,
        couponCount: payload.count,
        activationCount: payload.activationCount,
        // canCount: payload.canCount,
      });
    },
    updateBalance(state, { payload }) {
      return state.setIn(['account', 'balance'], payload.balanceYuan);
    },
    updateSumGift(state, { payload }) {
      return state.setIn(['gift', 'sum'], payload.sumDisAmount);
    },
    updateSmsLeftTime(state, { payload }) {
      let newState = state.set('sms', payload.time);
      if (payload.verToken) {
        newState = newState.set('verToken', payload.verToken);
      }
      return newState;
    },
    updateUser(state, { payload }) {
      const user = new User(payload);
      user.save();
      return state.set('user', user);
    },
  },
};
